package com.yr.ryjk.businessengine.task;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.Semaphore;

import com.yr.ryjk.businessengine.persistent.PersistentStorage;
import com.yr.ryjk.businessengine.persistent.PersistentStorageFactory;

/**
 * 任务管理器
 * @author Rick
 * 
 */
public class BaseTaskManager {
	private Semaphore lock = new Semaphore(0);

	private Vector<String> allTaskName = new Vector<String>();
	// here needs a thread safe container
	private Vector<BaseTask> allWaitingTask = new Vector<BaseTask>();
	// storage needs thread safe
	private PersistentStorage storage;

	public BaseTaskManager() {
		storage = PersistentStorageFactory.createPersistentStorage();
	}

	public void restore() {
		List<?> all = storage.restoreAll();
		for (Object o : all) {
			add(null, (BaseTask) o, false);
		}
	}

	@SuppressWarnings("finally")
	public BaseTask getTask() {
		
		BaseTask ret = null;
		try {
			lock.acquire();
			ret = (BaseTask) allWaitingTask.remove(0);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			return ret;
		}
	}
	
	public void add(BaseTask lastTask, BaseTask newTask, boolean isStore) {
		if(lastTask != null){
			if(newTask == lastTask){
				//update old task
				if (isStore && newTask.getIsNeedPersistent()) {
					storage.store(newTask.getStoreName(), newTask);
				}

				allWaitingTask.add(newTask);
				lock.release();
			}
		}
		if (!allTaskName.contains(newTask.storename)) {
			allTaskName.add(newTask.storename);
			allWaitingTask.add(newTask);
			if (isStore && newTask.getIsNeedPersistent()) {
				storage.store(newTask.getStoreName(), newTask);
			}
			lock.release();
//			System.out.println("add to taskmanager: " + task.getStoreName());
		}
	}

	public void removeStore(BaseTask task) {
		allTaskName.remove(task.getStoreName());
		storage.remove(task.getStoreName());
	}
}